package cn.itsource.ymcc.filter;

import cn.itsource.ymcc.config.ExcludeProperties;
import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.jwt.*;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.security.PublicKey;
import java.util.List;

@Slf4j
//@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Autowired
    private ExcludeProperties excludeProperties;
    //核心过滤
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //得到 token
        //1.先获取请求对象、响应对象  gateway是基于webflux/tomcat封装的，它的请求、响应对象与HttpServletRequest不一样了
        ServerHttpRequest request = exchange.getRequest();
        //当前请求的路径
        String value = request.getPath().value();
        //要放行的路径
        if(excludeProperties.isExcluded(value)){
            return chain.filter(exchange);
        }

        List<String> Headers = request.getHeaders().get(Constants.TOKEN);

        try {
            if(Headers != null && Headers.size() > 0){
                String token = Headers.get(0);//绝对是你的token
                //5.利用JWT工具类解析token   私钥加密 公钥解密
                JSONObject user = UserContext.getUser(token);
                //验证权限 todo
                if(user != null){
                    //token验证成功
                    return chain.filter(exchange);
                }

            }
        }catch (ExpiredJwtException e){
            e.printStackTrace();
        }


        ServerHttpResponse response = exchange.getResponse();
        //6.回“noLogin”
        response.getHeaders().set("content-type","application/json;charset=UTF-8");
        JsonResult jsonResult = JsonResult.error("noLogin");
        byte[] bytes = JSON.toJSONBytes(jsonResult);//阿里巴巴的json
        DataBuffer wrapper = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrapper));
    }














    @Override
    public int getOrder() {
        return 1;
    }
}
